package com.anyi.gulimall.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.anyi.gulimall.common.contants.ProductConstant;
import com.anyi.gulimall.common.es.SkuEsModel;
import com.anyi.gulimall.common.to.SkuHasStockVo;
import com.anyi.gulimall.common.to.SkuReductionTo;
import com.anyi.gulimall.common.to.SpuBoundTo;
import com.anyi.gulimall.common.utils.R;
import com.anyi.gulimall.product.dao.SpuInfoDescDao;
import com.anyi.gulimall.product.entity.*;
import com.anyi.gulimall.product.feign.CouponFeignService;
import com.anyi.gulimall.product.feign.SearchFeignService;
import com.anyi.gulimall.product.feign.WareFeignService;
import com.anyi.gulimall.product.service.*;
import com.anyi.gulimall.product.vo.Attr;
import com.anyi.gulimall.product.vo.BaseAttrs;
import com.anyi.gulimall.product.vo.SpuSaveVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import javafx.scene.chart.CategoryAxis;
import org.bouncycastle.asn1.esf.SPuri;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.anyi.gulimall.common.utils.PageUtils;
import com.anyi.gulimall.common.utils.Query;

import com.anyi.gulimall.product.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    private SpuInfoDescDao spuInfoDescDao;

    @Autowired
    private SpuImagesService spuImagesService;

    @Autowired
    private ProductAttrValueService productAttrValueService;

    @Autowired
    private SkuInfoService skuInfoService;

    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;


    @Autowired
    private CouponFeignService couponFeignService;

    @Autowired
    private SkuImagesService skuImagesService;

    @Autowired
    private BrandService brandService;

    @Autowired
    private AttrService attrService;

    @Autowired
    private WareFeignService wareFeignService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private SearchFeignService searchFeignService;



    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageCondition(Map<String, Object> params) {
        LambdaQueryWrapper<SpuInfoEntity> wrapper = new LambdaQueryWrapper<>();
        // 进行条件封装
        String  key = (String) params.get("key");
        Long catelogId = (Long) params.get("catelogId");
        Long brandId = (Long) params.get("brandId");

        if (!StringUtils.isEmpty(key)){
            wrapper.and((obj)->{
                obj.eq(SpuInfoEntity::getId,key).like(SpuInfoEntity::getSpuName,key);
            });
        }
        if (catelogId != null){
            wrapper.eq(SpuInfoEntity::getCatalogId,catelogId);
        }
        if (brandId !=null){
            wrapper.eq(SpuInfoEntity::getBrandId,brandId);
        }
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
             wrapper
        );
        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void saveProduct(SpuSaveVo spuSaveVo) {
        // 1.保存商品基本信息
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(spuSaveVo,spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        this.save(spuInfoEntity);
        // 保存描述信息
        Long spuId = spuInfoEntity.getId();
        SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
        spuInfoDescEntity.setSpuId(spuId);
        spuInfoDescEntity.setDecript(spuSaveVo.getSpuDescription());
        spuInfoDescDao.insert(spuInfoDescEntity);

        // 保存图片信息
        List<String> images = spuSaveVo.getImages();
        for (String image : images) {
            SpuImagesEntity spuImagesEntity = new SpuImagesEntity();
            spuImagesEntity.setSpuId(spuId);
            spuImagesEntity.setImgUrl(image);
            spuImagesService.save(spuImagesEntity);
        }
        // 保存基本销售属性 pms_sku_sale_attr_value
        List<BaseAttrs> baseAttrs = spuSaveVo.getBaseAttrs();
        List<ProductAttrValueEntity> productAttrValueEntities = baseAttrs.stream().map(item -> {
            ProductAttrValueEntity productAttrValueEntity = new ProductAttrValueEntity();
            productAttrValueEntity.setAttrValue(item.getAttrValues());
            productAttrValueEntity.setAttrId(item.getAttrId());
            productAttrValueEntity.setSpuId(spuId);
            productAttrValueEntity.setQuickShow(item.getShowDesc());
            return productAttrValueEntity;
        }).collect(Collectors.toList());
        productAttrValueService.saveBatch(productAttrValueEntities);

        // TODO 远程 保存积分信息 sms_spu_bounds
        SpuBoundTo spuBoundTo = new SpuBoundTo();
        spuBoundTo.setSpuId(spuId);
        spuBoundTo.setBuyBounds(spuSaveVo.getBounds().getBuyBounds());
        spuBoundTo.setGrowBounds(spuSaveVo.getBounds().getGrowBounds());
        R r = couponFeignService.saveBounds(spuBoundTo);
        if (r.getCode() !=0){
            log.error("远程保存spu积分信息失败");
        }


        // 保存sku信息
        spuSaveVo.getSkus().forEach(item->{
            // 保存sku基本信息
            SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
            BeanUtils.copyProperties(item,skuInfoEntity);
            skuInfoEntity.setBrandId(spuSaveVo.getBrandId());
            skuInfoEntity.setCatalogId(spuSaveVo.getCatalogId());

            skuInfoEntity.setSpuId(spuId);
            skuInfoService.save(skuInfoEntity);
            Long skuId = skuInfoEntity.getSkuId();
            // 保存销售信息
            List<Attr> attrs = item.getAttr();
            List<SkuSaleAttrValueEntity> saleAttrValueEntityList = attrs.stream().map(attr -> {
                SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                BeanUtils.copyProperties(attr, skuSaleAttrValueEntity);
                skuSaleAttrValueEntity.setSkuId(skuId);
                return skuSaleAttrValueEntity;
            }).collect(Collectors.toList());
            skuSaleAttrValueService.saveBatch(saleAttrValueEntityList);
            // 保存销售图片信息
            List<SkuImagesEntity> imagesEntities = item.getImages().stream().map(img -> {
                SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                BeanUtils.copyProperties(img, skuImagesEntity);
                skuImagesEntity.setSkuId(skuId);
                return skuImagesEntity;
            }).filter(imgEntity ->{
                // 过滤掉空的字符串
                return !StringUtils.isEmpty(imgEntity.getImgUrl());
            }).collect(Collectors.toList());
            skuImagesService.saveBatch(imagesEntities);

            // 远程保存折扣信息和会员价格
            SkuReductionTo skuReductionTo = new SkuReductionTo();
            BeanUtils.copyProperties(item, skuReductionTo);
            R r1 = couponFeignService.saveReductionAndMemberPrice(skuReductionTo);
            if (r1.getCode() !=0){
                log.error("远程保存spu折扣信息失败");
            }
        });
    }

    /**
     * 商品上架
     * @param spuId
     */
    @Transactional
    @Override
    public void up(Long spuId) {
        //1、查出当前spuId对应的所有sku信息,品牌的名字
        List<SkuInfoEntity> skuInfoEntities = skuInfoService.list(new LambdaQueryWrapper<SkuInfoEntity>().eq(SkuInfoEntity::getSpuId,spuId));

        // 4、查出当前sku的所有可以被用来检索的规格属性
        List<ProductAttrValueEntity> baseAttrs = productAttrValueService.list(new LambdaQueryWrapper<ProductAttrValueEntity>()
                .eq(ProductAttrValueEntity::getSpuId,spuId));

        List<Long> attrIds = baseAttrs.stream().map(attr -> attr.getAttrId()).collect(Collectors.toList());

        List<Long> searchAttrIds = attrService.selectSearchAttrs(attrIds);
        //转换为Set集合
        Set<Long> idSet = searchAttrIds.stream().collect(Collectors.toSet());

        List<SkuEsModel.Attrs> attrsList = baseAttrs.stream().filter(item -> {
            return idSet.contains(item.getAttrId());
        }).map(item -> {
            SkuEsModel.Attrs attrs = new SkuEsModel.Attrs();
            BeanUtils.copyProperties(item, attrs);
            return attrs;
        }).collect(Collectors.toList());

        List<Long> skuIdList = skuInfoEntities.stream()
                .map(SkuInfoEntity::getSkuId)
                .collect(Collectors.toList());
        //TODO 1、发送远程调用，库存系统查询是否有库存
        Map<Long, Boolean> stockMap = null;
        try {
            R skuHasStock = wareFeignService.getSkuHasStock(skuIdList);
            //
            TypeReference<List<SkuHasStockVo>> typeReference = new TypeReference<List<SkuHasStockVo>>() {};
            stockMap = skuHasStock.getData(typeReference).stream()
                    .collect(Collectors.toMap(SkuHasStockVo::getSkuId, item -> item.getHasStock()));
        } catch (Exception e) {
            log.error("库存服务查询异常：原因{}",e);
        }

        //2、封装每个sku的信息
        Map<Long, Boolean> finalStockMap = stockMap;
        List<SkuEsModel> collect = skuInfoEntities.stream().map(sku -> {
            //组装需要的数据
            SkuEsModel esModel = new SkuEsModel();
            esModel.setSkuPrice(sku.getPrice());
            esModel.setSkuImg(sku.getSkuDefaultImg());

            //设置库存信息
            if (finalStockMap == null) {
                esModel.setHasStock(true);
            } else {
                esModel.setHasStock(finalStockMap.get(sku.getSkuId()));
            }

            //TODO 2、热度评分。0
            esModel.setHotScore(0L);

            //TODO 3、查询品牌和分类的名字信息
            BrandEntity brandEntity = brandService.getById(sku.getBrandId());
            if(brandEntity !=null){
                esModel.setBrandName(brandEntity.getName());
                esModel.setBrandId(brandEntity.getBrandId());
                esModel.setBrandImg(brandEntity.getLogo());
            }


            CategoryEntity categoryEntity = categoryService.getById(sku.getCatalogId());
            if (categoryEntity !=null){
                esModel.setCatalogId(categoryEntity.getCatId());
                esModel.setCatalogName(categoryEntity.getName());
            }


            //设置检索属性
            esModel.setAttrs(attrsList);

            BeanUtils.copyProperties(sku,esModel);

            return esModel;
        }).collect(Collectors.toList());

        //TODO 5、将数据发给es进行保存：gulimall-search
        R r = searchFeignService.productStatusUp(collect);

        if (r.getCode() == 0) {
            //远程调用成功
            //TODO 6、修改当前spu的状态
            this.baseMapper.updaSpuStatus(spuId, ProductConstant.ProductStatusEnum.SPU_UP.getCode());
        } else {
            //远程调用失败
            //TODO 7、重复调用？接口幂等性:重试机制
        }

    }

}